#region license
/*
 * Copyright (C) 2007 CchenSoft.com
 * 
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License 2.1 or later, as
 * published by the Free Software Foundation. See the included License.txt
 * or http://www.gnu.org/copyleft/lesser.html for details.
 * 
 * Author: Billy Zhang
 */
#endregion

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Net;
using System.IO;
using System.Web.UI.WebControls;
using CchenSoft.Portal.Model;
using CchenSoft.Portal.Registry;
using CchenSoft.Portal.Util;
using System.Web;
using System.Web.UI.HtmlControls;
using CchenSoft.Portal.Service;
using CchenSoft.Portal.Spi.Registry;
using CchenSoft.Portal.Service.Impl;

namespace CchenSoft.Portal.Web
{
    [ParseChildren(true)]
    public class SingleControl : ThemeControl
    {
        private string hostName;
        private string portletContent;
        private PortletEntry entry;

        public SingleControl(string hostName, PortletEntry entry)
        {
            this.hostName = hostName;
            SkinFileName = "portlet_view.ascx";
            this.entry = entry;
            portletContent = ProcessPortletRequest();
        }
        //protected override 
        protected override void InitializeSkin(Control control)
        {
            //control.ID = instance.InstanceId;
            Label title = (Label)control.FindControl("title");
            title.Text = entry.Caption;

            Label content = (Label)control.FindControl("content");
            content.Text = portletContent;

            ((HyperLink)control.FindControl("hlnkCfg")).Visible = false;
            ((HyperLink)control.FindControl("hlnkMax")).Visible = false;
            ((HyperLink)control.FindControl("hlnkNormal")).Visible = false;
            ((HyperLink)control.FindControl("hlnkClose")).Visible = false;
        }

        private string GetRequestAction()
        {
            string action = entry.ViewPath;
            string queryString = PortalContext.Current.PortalURL.RequestParams.ToString();
            if (!string.IsNullOrEmpty(queryString))
                action += "?" + queryString;
            if (!action.StartsWith("/"))
                action = entry.RootPath + action;
            return action;
        }

        private Cookie TransformCookie(HttpCookie cookie)
        {
            Cookie result = new Cookie();
            result.Name = cookie.Name;
            result.Value = cookie.Values.ToString();
            result.Domain = HttpContext.Current.Request.Url.Host; // cookie.Domain;
            result.Expires = cookie.Expires;
            result.HttpOnly = cookie.HttpOnly;
            return result;
        }

        private string ProcessPortletRequest()
        {
            string action = GetRequestAction();
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(hostName + action);

            // set browsers environment.
            HttpRequest request = HttpContext.Current.Request;
            req.UserAgent = request.UserAgent;
            
            // add headers.
            req.Headers.Add("portal-url", PortalContext.Current.PortalURL.ToXml());
            req.Headers.Add("portal-exportservice", typeof(ExportServiceImpl).FullName);
            req.Headers.Add("portlet-name", entry.PortletId);

            if (req.CookieContainer == null)
                req.CookieContainer = new CookieContainer();

            HttpCookieCollection coll = HttpContext.Current.Request.Cookies;
            for (int i=0; i<coll.Count; i++)
            {
                Cookie cookie = TransformCookie(coll[i]);
                req.CookieContainer.Add(cookie);
            }

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

            StringBuilder ret = new StringBuilder();
            int BufferLengh = 8 * 1024;  // 16K

            using (StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8))
            {
                char[] buf = new char[BufferLengh];
                int len = sr.Read(buf, 0, BufferLengh);
                while (len > 0)
                {
                    ret.Append(new string(buf, 0, len));
                    len = sr.Read(buf, 0, BufferLengh);
                }
            }

            return ret.ToString();
        }
    }
}
